<template>
    <div class="departmentMain" :data-dept="queryParams.deptIds" >
        <el-select v-if="isHospital" v-model="queryParams.hospitalId" filterable placeholder="请选择医院" clearable
            :disabled="deptOptionsAble" :style="{ width: deptWidth }" @change="changeHospital" style="margin-right:10px;">
            <el-option v-for="item in deptOptionsArr" :key="item.deptId" :label="item.deptName"
                :value="item.deptId"></el-option>
        </el-select>
        <el-form-item :label="!isShowLabel?'科室':''" clearable v-if="isdepat">
            <el-select v-model="queryParams.deptId" filterable placeholder="请选择科室" clearable :style="{ width: deptWidth }"
                @change="changeHospitaldept" :disabled="deptIdOptiondisabled">

                <el-option v-for="item in deptOptionsArr0" :key="item.deptId" :label="item.deptName"
                    :value="item.deptId"></el-option>
            </el-select>
        </el-form-item>
        <!-- :disable-branch-nodes="true" :labelInValue="true"-->
        <treeselect :defaultExpandLevel="Infinity" v-if="isAdd&&!Optiohospitals" v-model="queryParams.deptIds" noResultsText="暂无"
            :style="{ width: deptWidth }" :options="deptOptions" @select="handleSelect" :class="isHeight?'treeSelectH':''"
            :disabled="isdisabled || deptIdsdisabled" :normalizer="normalizer" @deselect="handleDeSelect"
            @input="handleDeSelect0" :clearable="true" placeholder="请选择科室" :labelInValue="true" :multiple="false"
            :disable-branch-nodes="true"
            />
            <treeselect :defaultExpandLevel="Infinity" v-if="isAdd&&Optiohospitals" v-model="queryParams.deptIds" noResultsText="暂无"
            :style="{ width: deptWidth }" :options="deptOptions" @select="handleSelect" :class="isHeight?'treeSelectH':''"
            :disabled="isdisabled || deptIdsdisabled" :normalizer="normalizer" @deselect="handleDeSelect"
            @input="handleDeSelect0" :clearable="true" placeholder="请选择科室" :labelInValue="true" :multiple="false"
            />
    </div>
</template>
<script>
import { mapGetters } from "vuex";
import Cookies from "js-cookie";
import {
    deptTreeSelect,
} from "@/api/system/user";
import { listDept, listAllDept,deptBuyUseList} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    name: 'department',
    props: ['isHospital','Optiohospitals','isdepat','isShowLabel', "isAdd","isHeight", "deptIds", "HospitalId", 'isdisabled', 'deptWidth', 'isAllDept','isClearDept','isUserAll'],
    data() {
        return {
            // 科室树选项
            deptOptions: undefined,
            // 科室名称
            deptName: undefined,
            queryParams: {
                deptId: undefined,
                deptIds: undefined,
                hospitalId: ""
            },
            ModeTree_lables: [],//选中的项
            deptOptionsArr: [],//医院
            deptOptionsArr0: [],//门诊
            deptOptionsAble: false,
            deptIdsdisabled: false,
            deptIdOptiondisabled:false,
            AllOptions: [],//所有过滤的数据
        }
    },
    components: { Treeselect },
    computed: {
        ...mapGetters(["dept", "hospital","affiliatedHospitalFlag"]),
    },
    mounted() {
        console.log(this.dept)
       
        if (this.deptIds) {
            console.log(this.deptIds)
            this.queryParams.deptIds = this.deptIds
        } else {
            // console.log("000022@")
            this.queryParams.deptIds = undefined
        }
        if (this.HospitalId) {
            this.queryParams.hospitalId = this.HospitalId
        } else {
            this.queryParams.hospitalId = ''
        }
        if (this.isAllDept) {
            this.getlistAllDept()
        } else {
            if(this.affiliatedHospitalFlag){
                if(this.isUserAll){
                    this.getdeptBuyUseList()
                }else{
                    this.getlistDept()
                }

            }else{
                this.getlistDept()
            }


        }

    },
    watch: {
        // 根据名称筛选科室树 this.$refs.tree.filter(val);
        "queryParams.deptIds": function (val, oldVal) {
            const currentDeptId = Cookies.get("currentDeptId");
            if (val) {
                // console.log("000改变了")
                this.queryParams.deptIds = val
            } else {
                if(currentDeptId){
                    this.queryParams.deptIds=Number(currentDeptId)
                  }else{
                    this.queryParams.deptIds = undefined
                  }
                // this.queryParams.deptIds = undefined
            }
        },
        "queryParams.hospitalId": function (val, oldVal) {
            const currentDeptId = Cookies.get("currentDeptId");
                 
            if (val) {
                // console.log(val)
                // this.changedepatIds(val)
                // console.log("关闭")
                this.queryParams.hospitalId = val
                if(!this.deptOptionsAble){
                    if(currentDeptId){
                    this.queryParams.deptId=Number(currentDeptId)
                  }else{
                    this.queryParams.deptId = undefined
                  }
                    
                }

            } else {
                // console.log("000")
                if(currentDeptId){
                    this.queryParams.deptId=Number(currentDeptId)
                  }else{
                    this.queryParams.deptId = undefined
                  }
            }
        },
        isClearDept:{
          handler(val,oldVal){
            if(val){
              console.log('isClearDept---',val,oldVal)
              this.queryParams.hospitalId=''
              this.queryParams.deptId=''
            }
          },
          immediate: true
        }
    },
    methods: {
        handleDeSelect0() {
            if (this.queryParams.deptIds == undefined) {
                this.ModeTree_lables = []
                this.changedepatIds()
            }

        },
        //处理数据
        getData(data){
            let that = this
            console.log("departM")
            console.log(data)
            if (that.getSplit(that.dept.ancestors).length == 3) {//3级用户
                    data.push(that.hospital)//默认加一个上级医院
                }
                this.AllOptions = data
                let editOptions = data
                let dataArr0 = []
                if (that.HospitalId) {//如果编辑修改有医院，默认只能选这个医院下面的科室
                    if (editOptions && editOptions.length > 0) {
                        editOptions.forEach(function (ele) {
                            if ((that.getSplit(ele.ancestors).length == 2 && ele.deptId == that.HospitalId) || (that.getSplit(ele.ancestors).length == 3 && ele.parentId == that.HospitalId)) {
                                console.log("---进来了么--")
                                dataArr0.push(ele)
                            }
                        })
                    }
                } else {
                    dataArr0 = data
                }
                // console.log("dataArr0")
                //console.log(dataArr0)
                // console.log("djihahdhnnhas///////////////////////////////////////")
                // console.log(that.getSplit(that.dept.ancestors).length)
                if (that.getSplit(that.dept.ancestors).length == 1 && that.HospitalId) {
                    this.deptOptions = this.handleTree(dataArr0, "deptId");
                } else {
                    if(that.Optiohospitals&&that.getSplit(that.dept.ancestors).length == 2){
                        this.deptOptions = this.handleTree(dataArr0, "deptId");
                    }else{
                        this.deptOptions = this.handleTree(dataArr0, "deptId")[0].children;
                    }
                    
                }
                // console.log(this.deptOptions)
                // console.log("----******************************")
                // console.log(this.deptOptions)
                if (this.isAdd) {
                    this.deptIdsdisabled = false
                    if (this.deptOptions && this.deptOptions.length == 1) {
                        if (that.getSplit(this.deptOptions[0].ancestors).length == 3) {

                            this.queryParams.deptIds = this.deptOptions[0].deptId
                            // console.log(this.queryParams.deptIds)
                          
                            this.deptIdsdisabled = true
                        }
                    }
                    this.$emit('changedepatData', this.deptOptions)
                }
                let dataArr = []
                if (data && data.length > 0) {
                    data.forEach(function (ele) {
                        if (that.getSplit(ele.ancestors).length == 2) {
                            dataArr.push(ele)
                        }
                    })
                }
                if (dataArr.length > 0) {
                    if (dataArr && dataArr.length == 1) {
                        that.queryParams.hospitalId = dataArr[0].deptId
                        that.deptOptionsAble = true
                        that.deptOptionsArr = dataArr
                        that.getdeptOptionsArr0(that.queryParams.hospitalId,1)
                        return false
                    } else {
                        //that.queryParams.hospitalId = dataArr[0].deptId
                    }
                    that.deptOptionsArr = dataArr
                }
                if (this.isHospital) {
                    let params = {
                        hospitalId: that.queryParams.hospitalId,
                        deptId: that.queryParams.deptIds
                    }
                    that.$emit("refreshData", params)
                }
        },
        //勾选 医院筛选  deptBuyUseList
        getdeptBuyUseList(){
          let that = this
            deptBuyUseList().then(response => {
                let data = response.data
                that.getData(data)

            });
        },
        // 获取所有医院及部门
        getlistAllDept() {
          let that = this
            listAllDept().then(response => {
                let data = response.data
                that.getData(data)

            });
        },
        // 医院
        getlistDept() {
          let that = this
            listDept().then(response => {
                let data = response.data
                that.getData(data)
            //   console.log('getlistDept--response',response)

            });
        },
        getdeptOptionsArr0(id,type) {
            // console.log(id)
            let data = this.AllOptions
            let dataArr = []
            this.deptOptionsArr0 = []
            if (data && data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    if (data[i].parentId == id) {
                        dataArr.push(data[i])
                    }
                }
            }
         
            this.deptOptionsArr0 = dataArr
            if(type==1){
                if(dataArr&&dataArr.length==1){
                this.queryParams.deptId=dataArr[0].deptId
                this.deptIdOptiondisabled=true
                if (this.isHospital) {
                    let params = {
                        hospitalId:this.queryParams.hospitalId,
                        deptId:this.queryParams.deptId
                    }
                    this.$emit("refreshData", params)
                }
            }else{
                const currentDeptId = Cookies.get("currentDeptId");
     
                 if(this.queryParams.deptId==''||this.queryParams.deptId==undefined||this.queryParams.deptId==null){
                    this.queryParams.deptId=currentDeptId?Number(currentDeptId):''
                    //this.deptIdOptiondisabled=true
                 }
                if (this.isHospital) {
                    let params = {
                        hospitalId:this.queryParams.hospitalId,
                        deptId: this.queryParams.deptId
                    }
                    this.$emit("refreshData", params)
                }
             }
            }


        },
        reset() {
            let that = this
            if (that.deptOptionsAble) {
                if(that.deptIdOptiondisabled){

                }else{
                    that.queryParams.deptId = undefined
                }
            } else {
                that.queryParams.deptId = undefined
                that.queryParams.hospitalId = ''
            }
            let params = {
                hospitalId: that.queryParams.hospitalId,
                deptId: that.queryParams.deptId
            }
            that.$emit("refreshData", params)
        },
        changeHospital() {
            let that = this
            if (that.queryParams.hospitalId) {
                that.queryParams.deptId = undefined
                that.getdeptOptionsArr0(that.queryParams.hospitalId)
            } else {
                that.queryParams.deptId = undefined
                that.deptOptionsArr0 = []
            }
            let params = {
                hospitalId: that.queryParams.hospitalId,
                deptId: that.queryParams.deptId
            }
            console.log("________9999")
            that.$emit("refreshData", params)
        },
        changeHospitaldept() {
            let that = this
            let params = {
                hospitalId: that.queryParams.hospitalId,
                deptId: that.queryParams.deptId
            }
            that.$emit("refreshData", params)
        },
        handleDeSelect(node) {//删除
            console.log("删除")
            for (let i = 0; i < this.ModeTree_lables.length; i++) {
                if (node.id == this.ModeTree_lables[i].id) {
                    this.ModeTree_lables.splice(i, 1);
                    this.changedepatIds()
                }
            }
        },
        handleSelect(node) {//勾选
            this.ModeTree_lables.push(node);
            this.changedepatIds()
        },
        changedepatIds() {
            console.log(this.ModeTree_lables)
            this.$emit('changedepatData', this.ModeTree_lables)
        },
        getSplit(str) {
            return str.split(',')
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.deptId,
                label: node.deptName,
                children: node.children
            };
        },

    },
}
</script>

<style lang="scss" scoped>
.treeSelectH{
    height:28px !important;
}
::v-deep .treeSelectH .vue-treeselect__control{
    height:26px !important;
}
::v-deep .treeSelectH .vue-treeselect__placeholder, ::v-deep .treeSelectH .vue-treeselect__single-value{
    line-height: 28px;
    font-size:12px;
}
.departmentMain {
    height: 32px !important;

}

::v-deep .vue-treeselect--has-value .vue-treeselect__input {
    height: 32px;
    line-height: 32px;
}

::v-deep .el-form-item {
    margin-right: 0px !important;
}

::v-deep #printBox table {
    border: 1px solid #ddd;
    border-collapse: collapse;
}

::v-deep #printBox td {
    border: 1px solid #ddd;
    height: 40px;
    padding-left: 5px;
}

::v-deep #printBox img {
    max-width: 100%;
}

::v-deep .el-input__inner {
    height: 32px;
    line-height: 32px;
}

::v-deep .vue-treeselect--has-value .vue-treeselect__multi-value {
    margin-bottom: 0px;
    height: 32px;
}

::v-deep .vue-treeselect__multi-value-item {
    height: 28px;
    padding: 0px;
}

::v-deep .vue-treeselect__multi-value-label {
    height: 28px;
    line-height: 28px;
}

::v-deep .vue-treeselect__multi-value-item-container {
    height: 32px;
    padding-top: 0px;
}

::v-deep .el-form-item--medium .el-form-item__content {
    line-height: 32px !important;
}
</style>

